package com.qfmy.web.service.impl;

import com.qfmy.web.enmu.ResultCode;
import com.qfmy.web.entity.login.LoginUser;
import com.qfmy.web.exception.BaseException;
import com.qfmy.web.mapper.LoginUserMapper;
import com.qfmy.web.service.LoginUserService;
import com.qfmy.web.utils.JwtUtil;
import com.qfmy.web.utils.LoginUserHolder;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;



import java.time.LocalDateTime;


@SuppressWarnings("all")
@Service
public class LoginUserImpl implements LoginUserService {
   //注入LoginUserMapper
    @Resource
    private LoginUserMapper loginUserMapper;
    //注入redis
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void register(String userName, String password, String phone) {
        LoginUser user = new LoginUser();
        user.setUsername(userName);
        user.setPassword(password);
        user.setPhone(phone);
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        //对密码进行加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        user.setPassword(password);
        //调用插入方法
        loginUserMapper.insertUser(user);
    }

    /**
     * 获取登录用户
     * @return
     */
    @Override
    public LoginUser getLoginUser() {
        //从当前线程中获取登录用户
        Claims claims = ( Claims)LoginUserHolder.get();
        //获取用户id
        Long id = claims.get("id", Long.class);
        //根据用户id查询用户信息
        LoginUser loginUser = loginUserMapper.selectById(id);
        return loginUser;
    }

    /**
     * 更新用户信息
     * @param id
     */
    @Override
    public void updateById(@NotNull LoginUser loginUser) {
        //从当前线程中获取登录用户
        Claims claims = ( Claims)LoginUserHolder.get();
        //获取用户id
        Long id = claims.get("id", Long.class);
        //根据用户id查询用户信息
        //设置修改时间
        loginUser.setUpdateTime(LocalDateTime.now());
        //调用更新方法
        loginUserMapper.updateById(loginUser,id);
    }


    @Override
    public String login(String username, String password) {
        //根据用户名称查询用户信息
       LoginUser user = loginUserMapper.selectByUserName(username);
       //判断用户是否存在
       if(user == null){
          throw new BaseException(ResultCode.ACCOUNT_NOT_EXIST_ERROR);
       }
       //获取密码
        String pw = user.getPassword();
       //对密码进行加密
        String s = DigestUtils.md5DigestAsHex(password.getBytes());
        //判断密码是否正确
        if(!pw.equals(s)){
            throw new BaseException(ResultCode.PASSWORD_ERROR);
        }
        //生成jwt
        String token = JwtUtil.createToken(user.getId(),username);
        //返回token
        return token;
    }


}
